import path from 'path';
import DBConnectTool from '../../../com/DBTool/DBConnectTool';
import compressible from '../../FSTool/compressible';
import zlibPromise from '../../FSTool/zlibPromise';

type FileInfo = {
	fileName: string,
	relativePath: string,
	buffer: Buffer,
	md5: string,
	file_size: number,
	file_zip: string
}

// 保存文件列表到数据库，默认不压缩，大小不超过 250 mb
async function saveListToDB(DBName: string, fileInfo: FileInfo[], needCompress = false) {

	if (!fileInfo.length) {
		return true;
	}

	let fileInfoSqlSum = 'INSERT OR IGNORE INTO file_info  (file_name, file_path, file_zip, file_size, file_md5) VALUES ';

	let fileDataSqlSum = 'INSERT OR IGNORE INTO file_data (file_md5, file_data) VALUES ';

	const startCompressTime = new Date().getTime();
	for (let i = 0; i < fileInfo.length; i++) {
		const fileItem = fileInfo[i];

		if (!fileItem.buffer || !fileItem.relativePath) {
			continue;
		}

		let buffer = fileItem.buffer;
		let compressType = fileItem.file_zip || '';
		const relativePath = fileItem.relativePath;
		const md5 = fileItem.md5 || require('crypto').createHash('md5').update(buffer).digest('hex');
		const size = fileItem.file_size || buffer.length;

		const fileName = fileInfo[i].fileName || path.basename(fileItem.relativePath);
		let file_path = path.dirname(fileItem.relativePath);
		file_path = file_path === '\\' ? '\\' : file_path + '\\';
		file_path = file_path.replaceAll('/', '\\');

		if (needCompress && buffer && compressible(relativePath) && !fileItem.file_zip) {
			buffer = await zlibPromise.zip(buffer);
			compressType = 'gzip';
		}
		fileInfoSqlSum += `('${fileName}', '${file_path}', '${compressType}', ${size}, '${md5}'),`;
		fileDataSqlSum += `('${md5}', X'${buffer.toString('hex')}'),`;
	}
	const endCompressTime = new Date().getTime();

	try {
		const startSaveTime = new Date().getTime();
		const dbTool = await DBConnectTool.openDB(DBName);
		const {changes: changesInfo} = await dbTool.sqlite3Promise.insertData(fileInfoSqlSum.substring(0, fileInfoSqlSum.length - 1), []);
		const {changes: changesData} = await dbTool.sqlite3Promise.insertData(fileDataSqlSum.substring(0, fileDataSqlSum.length - 1), []);
		const endSaveTime = new Date().getTime();

		return {
			changesInfo,
			changesData,
			compressTime: endCompressTime - startCompressTime,
			saveTime: endSaveTime - startSaveTime
		};
	} catch (e) {
		console.log(e);
		return false;
	}
}


export default saveListToDB;
